/*
 * @Author: caiqi
 * @Date: 2019-02-14 14:34:34
 * @Last Modified by: cai.qi
 * @Last Modified time: 2020-05-13 19:28:52
 * @Describe:
 */

"use strict";

import { Service } from "egg";
import wxConfig from '../../config/wx'

// sha1加密
function sha1(str) {
    const crypto = require('crypto');
    let shasum = crypto.createHash("sha1")
    shasum.update(str)
    str = shasum.digest("hex")
    return str
}

/**
 * 生成签名的时间戳
 * @return {字符串}
 */
function createTimestamp() {
    return new Date().getTime() / 1000 + ''
}

/**
 * 生成签名的随机串
 * @return {字符串}
 */
function createNonceStr() {
    return Math.random().toString(36).substr(2, 15)
}

/**
 * 对参数对象进行字典排序
 * @param  {对象} args 签名所需参数对象
 * @return {字符串}    排序后生成字符串
 */
function raw(args) {
    let keys = Object.keys(args)
    keys = keys.sort()
    let newArgs = {}
    keys.forEach((key) => {
        newArgs[key.toLowerCase()] = args[key]
    })

    let string = ''
    for (let k in newArgs) {
        string += '&' + k + '=' + newArgs[k]
    }
    string = string.substr(1)
    return string
}

export default class TypeService extends Service {
    // ------------------------------ get_access_token
    async get_access_token() {
        const { app } = this
        // await app.redis.del('access_token');
        const _access_token = await app.redis.get('access_token');
        if (_access_token) {
            return _access_token
        } else {
            const _url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxConfig.appId}&secret=${wxConfig.appSecret}`
            const res = await this.ctx.curl(_url, {
                method: "GET",
                dataType: "json",
            });
            await app.redis.set('access_token', res.data.access_token, 'EX', 7000);
            return res.data.access_token
        }
    }

    // ------------------------------ get_access_token
    async get_ticket() {
        const { app, ctx } = this
        // await app.redis.del('wx_ticket');
        const access_token = await ctx.service.sevWx.get_access_token();
        const _wx_ticket = await app.redis.get('wx_ticket');
        console.log('_wx_ticket', _wx_ticket)
        if (_wx_ticket) {
            return _wx_ticket
        } else {
            const _url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`
            const res = await this.ctx.curl(_url, {
                method: "GET",
                dataType: "json",
            });
            console.log('wx_ticket', res.data.ticket)
            await app.redis.set('wx_ticket', res.data.ticket, 'EX', 7000);
            return res.data.ticket
        }
    }




    async get_sdk_config() {
        const { ctx } = this
        const ticket = await ctx.service.sevWx.get_ticket();
        let ret: any = {
            jsapi_ticket: ticket,
            nonceStr: createNonceStr(),
            timestamp: createTimestamp(),
            url: 'http://192.168.1.121:8080/home'
        };

        let string = raw(ret)
        ret.signature = sha1(string)
        ret.appId = wxConfig.appId;
        console.log('ret', ret)
        return ret
    }
}
